package no.ntnu.item.ttm4115.termproject.positionagent.data;


	import java.io.*;
	import java.util.*;
import javax.comm.*;

	public class GpsDataRead implements Runnable, SerialPortEventListener {
		static CommPortIdentifier portId;
		static Enumeration portList;
		
		static List dataList = new LinkedList();
		 static private double lati;
		static private double longi;
		InputStream inputStream;
		SerialPort serialPort;
		Thread readThread = new Thread(this);;
		//Thread troden;
		
		
		public GpsDataRead(boolean fromAgent){
			
			
			System.out.println("called...");
			// -Djava.library.path=lib 
			try{
				System.setProperty("driver", "gnu.io.RXTXCommDriver");
				//System.setProperty("-Djava.library.path",".");
				// copy rxtxSerial.dll to the ..\jredirectory\bin
				System.loadLibrary("rxtxSerial");
				
				System.out.println("lib loaded...");

			}
			catch(Exception e){
				System.err.println("Err: in loading properties");
			}
			
			portList = CommPortIdentifier.getPortIdentifiers();

			while (portList.hasMoreElements()) {
				portId = (CommPortIdentifier) portList.nextElement();
				if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
					if (portId.getName().equals("COM24")) {
						// if (portId.getName().equals("/dev/term/a")) {
						System.out.println("start to read data...");
						GpsDataRead reader = new GpsDataRead();
					}
				}
			}
		}
		public double getLat(){
			return lati;
		}
		public void setLat(double lat){
			lati = lat;
		}
		public void setLong(double lon){
			longi = lon;
		}
		public double getlong(){
			return longi; 
		}
		public static void main(String[] args) {
			
			// -Djava.library.path=lib 
			try{
				//System.setProperty("driver", "gnu.io.RXTXCommDriver");
				//System.setProperty("-Djava.library.path",".");
				// copy rxtxSerial.dll to the ..\jredirectory\bin
				//System.loadLibrary("rxtxSerial");

			}
			catch(Exception e){
				System.err.println("Err: in loading properties");
			}
			
			portList = CommPortIdentifier.getPortIdentifiers();

			while (portList.hasMoreElements()) {
				portId = (CommPortIdentifier) portList.nextElement();
				if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
					if (portId.getName().equals("COM22")) {
						// if (portId.getName().equals("/dev/term/a")) {
						GpsDataRead reader = new GpsDataRead();
					}
				}
			}
		}
		
		

		public GpsDataRead() {
			try {
				System.out.println("initing port...");
				serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
			} catch (PortInUseException e) {System.out.println(e);}
			try {
				inputStream = serialPort.getInputStream();
			} catch (IOException e) {System.out.println(e);}
			try {
				serialPort.addEventListener(this);
			} catch (TooManyListenersException e) {System.out.println(e);}
			serialPort.notifyOnDataAvailable(true);
			try {
				serialPort.setSerialPortParams(38400,
						SerialPort.DATABITS_8,
						SerialPort.STOPBITS_1,
						SerialPort.PARITY_NONE);
			} catch (UnsupportedCommOperationException e) {System.out.println(e);}
			//readThread = new Thread(this);
			readThread.start();
			//readThread.start();
		}

		public void run() {
			try {
				System.out.println("Hei er vi i run");
				System.out.println("sleeping.....");
				readThread.sleep(10000);
			} catch (InterruptedException e) {System.out.println(e);}
		}

		public void serialEvent(SerialPortEvent event)  {
			//troden = new Thread(this);
			//troden.start();
			switch(event.getEventType()) {
			case SerialPortEvent.BI:
			case SerialPortEvent.OE:
			case SerialPortEvent.FE:
			case SerialPortEvent.PE:
			case SerialPortEvent.CD:
			case SerialPortEvent.CTS:
			case SerialPortEvent.DSR:
			case SerialPortEvent.RI:
			case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
				break;
			case SerialPortEvent.DATA_AVAILABLE:
				byte[] readBuffer = new byte[100];
				int pos = 0;
				try {
					// reading the data available at the inputstream
					while (inputStream.available() > 0) {			
						byte[] srcBuffer = new byte[20];
						int numBytes = inputStream.read(srcBuffer);					
						System.arraycopy(srcBuffer, 0, readBuffer, pos, numBytes);
						pos = pos + numBytes;
					}
					// putting the data into the linked list
					dataList.add(new String(readBuffer,0,pos));
				} catch (Exception e) {System.out.println("err: "+e);}
				
				// populating the data as string..retrieving from linked list
				String data="";
				Iterator i = dataList.iterator();
				while(i.hasNext()){

						data+=i.next();
						//readThread.sleep(10000);
						//troden.sleep(50000);
					
					
				}
			
					
					//readThread.sleep(10000);
					
			
				// spliting the data into sentences (lines)
				String [] temp = data.split("\n");
				for(int j=0;j<temp.length;j++){
					String [] temprmc = temp[j].split(",");
					if(temp[j].contains("$GPRMC") && (temprmc.length>=7)) // to make sure that sufficient information is available
					{
							parseGPRMC(temp[j]);
						//System.out.println("parsed: "+ parseGPRMC(temp[j]));
						//location = Double.parseDouble(parseGPRMC(temp[j]));
					}
				}
				
				break;
			}
		}
		
		// method to parse GPRMC string
		/* $GPRMC,004007,V,3748.410,N,12226.632,W,000.0,360.0,130102,015.7,E*6F */
		/* $GPRMC,time,V or A,ddmm.mmm,N or S,dddmm.mmm,W or E,000.0,360.0,130102,015.7,E*6F */
		public String parseGPRMC(String data)
		{
			//System.out.println("GPRMC String: "+ data);
			String computed = "";
			String lat = "", latSgn = "", lon = "", lonSgn = "";
			String nmeaKey = "";
			try { nmeaKey = data.substring(3, 6) ;}
			catch (Exception e)
			{ return ""; }
			if (nmeaKey.equals("RMC"))
			{	//System.out.println("key: "+ nmeaKey);
				/* $GPRMC,004007,V,3748.410,N,12226.632,W,000.0,360.0,130102,015.7,E*6F */
				if (data.indexOf(",V,") > -1)
				{  // That's what we're interested in.
					// Example : [$GPRMC,004007,A,3748.410,N,12226.632,W,000.0,360.0,130102,015.7,E*6F]
					String tmp = data.substring(data.indexOf(",V,") + ",V,".length());  
					// tmp is now : [3748.410,N,12226.632,W,000.0,360.0,130102,015.7,E*6F]
					if (tmp.indexOf(",") > -1) // Latitude Value
					{
						lat = tmp.substring(0, tmp.indexOf(","));
						
						tmp = tmp.substring(tmp.indexOf(",") + ",".length());
						// tmp is now : [N,12226.632,W,000.0,360.0,130102,015.7,E*6F]
					}
					if (tmp.indexOf(",") > -1) // Latitude Sign
					{
						latSgn = tmp.substring(0, tmp.indexOf(","));
						tmp = tmp.substring(tmp.indexOf(",") + ",".length());
						// tmp is now : [12226.632,W,000.0,360.0,130102,015.7,E*6F]
					}
					if (tmp.indexOf(",") > -1) // Longitude Value
					{
						lon = tmp.substring(0, tmp.indexOf(","));
						
						tmp = tmp.substring(tmp.indexOf(",") + ",".length());
						// tmp is now : [W,000.0,360.0,130102,015.7,E*6F]
					}
					if (tmp.indexOf(",") > -1) // Longitude Sign
					{
						lonSgn = tmp.substring(0, tmp.indexOf(","));
						tmp = tmp.substring(tmp.indexOf(",") + ",".length());
						// tmp is now : [000.0,360.0,130102,015.7,E*6F]
					}
				}
			}
			if (lat.length() > 0)
			{
				if (lat.indexOf(".") > -1)
				{
					System.out.println("skriver lati");
					String s = lat.substring(0, lat.indexOf("."));
					System.out.println(s.substring(0, s.length()));
					System.out.println(lat.substring(s.length() - 2));
					s = s.substring(0, s.length() - 2) + lat.substring(s.length() - 2);
					lat = s;
					//lati = Double.parseDouble(lat);
					setLat(Double.parseDouble(lat));
					System.out.println(lati);
				}
			}
			else
				lat = "Not Set";
			if (lon.length() > 0)
			{
				if (lon.indexOf(".") > -1)
				{
					System.out.println("skriver longi");
					String s = lon.substring(0, lon.indexOf("."));
					s = s.substring(0, s.length() - 2) + lon.substring(s.length() - 2);
					lon = s;
					//longi = Double.parseDouble(lon);
					setLong(Double.parseDouble(lon));
					System.out.println(longi);
				}
			}
			else
				lon = "Not Set";
				
			computed = latSgn + " " + lat + "/" + lonSgn + " " + lon;
			return computed;
		}	
	}


